#ifdef _WIN32
#include <WinSock2.h>
#include <WS2tcpip.h>
#include <MSWSock.h>
#else
#include <arpa/inet.h>
#include <netdb.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#endif // _WIN32
#include <string.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>
#include <errno.h>

#include <chrono>
#include <string>
#include <iostream>
#include <mutex>
#include <condition_variable>
#include <unordered_map>
#include <memory>

constexpr int MAX_LEN = 256;
constexpr int MAX_BUF = 4096;
#ifndef _WIN32
typedef int SOCKET;
#define CLOSESOCKET close
#else
#define CLOSESOCKET closesocket
#pragma comment(lib, "ws2_32.lib")
#endif // !_WIN32

int main(int argc, char *argv[]) {
    SOCKET listen_fd, client_fd, sockfd;
    int i, max_i, max_fd;
    int nready, port, client[FD_SETSIZE];
    int n, ret;
    fd_set rset, allset;
    char recv_buff[MAX_BUF];
    socklen_t client_len;
    struct sockaddr_in server_addr, client_addr;

    if (argc != 2) {
        printf("usage: server <port>\n");
        return -1;
    }

#ifdef _WIN32
    WSADATA data;
    int status;
    status = WSAStartup(MAKEWORD(2, 0), &data);
    if (status != 0) {
        printf("failed to init win sock\n");
        return -1;
    }
#endif // _WIN32
    port = atoi(argv[1]);

    printf("using port: %d\n", port);

    if ((listen_fd = socket(AF_INET, SOCK_STREAM, 0)) == (SOCKET)(-1)) {
        printf("failed to create socket\n");
        return -1;
    }

    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(port);
    server_addr.sin_addr.s_addr = htonl(INADDR_ANY);

    bind(listen_fd, (struct sockaddr *)&server_addr, sizeof(server_addr));

    listen(listen_fd, 128);

    max_fd = listen_fd;
    max_i = -1;

    for (i = 0; i < FD_SETSIZE; i++) {
        client[i] = -1;
    }

    FD_ZERO(&allset);
    FD_SET(listen_fd, &allset);

    while (true) {
        rset = allset;
        nready = select(max_fd + 1, &rset, NULL, NULL, NULL);

        if (FD_ISSET(listen_fd, &rset)) {
            printf("accept event ...\n");
            client_len = sizeof(client_addr);
            client_fd = accept(listen_fd, (struct sockaddr *)&client_addr, &client_len);
            if (client_fd < 0) {
                printf("accept error: %s\n", strerror(errno));
                exit(1);
            }

            printf("accept a client(%d): [%s:%d]\n", (int)client_fd,
                   inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));

            // add client
            for (i = 0; i < FD_SETSIZE; i++) {
                if (client[i] < 0) {
                    client[i] = client_fd;
                    break;
                }
            }
            if (FD_SETSIZE == i) {
                printf("too many connections.\n");
                CLOSESOCKET(client_fd);
                continue;
            }

            FD_SET(client_fd, &allset);
            if (client_fd > max_fd) max_fd = client_fd;
            if (i > max_i) max_i = i;
            if (--nready < 0) continue;
        }

        for (i = 0; i <= max_i; i++) {
            sockfd = client[i];
            if ((int)sockfd < 0) continue;
            if (FD_ISSET(sockfd, &rset)) {
                // client request
                n = recv(sockfd, recv_buff, MAX_BUF - 1, 0);
                if (n <= 0) {
                    printf("client(%d) closed!\n", (int)sockfd);
                    FD_CLR(sockfd, &allset);
                    CLOSESOCKET(sockfd);
                    client[i] = -1;
                } else {
                    printf("received %d bytes from client(%d).\n", n, (int)sockfd);
                    ret = send(sockfd, recv_buff, n, 0);
                    if (ret != n) {
                        printf("client(%d) send data error.\n", (int)sockfd);
                        break;
                    }
                }
                if (--nready <= 0) break;
            }
        }
    } // end while

    CLOSESOCKET(listen_fd);
#ifdef _WIN32
    WSACleanup();
#endif // _WIN32
    return 0;
}
